const app = getApp()
var myrequest = require('../../utils/util.js')

Page({
  data: {
    productId: app.globalData.productId,
    deviceName: app.globalData.deviceName,
    stateReported: {},
    carts: [], // 购物车列表
    // listcarts : [], //显示在去结算的小括号里面
    totalPrice: 0, // 总价，初始为0
    selectAllStatus: true, // 全选状态，默认全选
    id :99,
    num :99,
    price: 99,
    name: "错误"
  }, 
  // onLoad: function (options) {
  //   console.log("index onLoad")
  //   if (!app.globalData.productId) {
  //     wx.showToast({
  //       title: "产品ID不能为空",
  //       icon: 'none',
  //       duration: 3000
  //     })
  //     return
  //   } else if (!app.globalData.deviceName) {
  //     wx.showToast({
  //       title: "设备名称不能为空",
  //       icon: 'none',
  //       duration: 3000
  //     })
  //     return
  //   }
  //  //这一句先前demo已经注释了 // this.update()
  // },

  //购物车选择
  selectList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    const selected = carts[index].selected;
    carts[index].selected = !selected;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },

   //删除购物车当前商品
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    carts.splice(index, 1);
    this.setData({
      carts: carts
    });
    if (!carts.length) {
      this.setData({
        hasList: false
      });
    } else {
      this.getTotalPrice();
    }
  },

  //购物车全选事件
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;
 
    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts
    });
    this.getTotalPrice();
  },

  //计算总价
  getTotalPrice() {
    let carts = this.data.carts; // 获取购物车列表
    let total = 0;
    for (let i = 0; i < carts.length; i++) { // 循环列表得到每个数据
      if (carts[i].selected) { // 判断选中才会计算价格
        total += carts[i].num * carts[i].price; // 所有价格加起来
      }
    }
    this.setData({ // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  },

  去结算: function(e){  //要带数据跳转
    console.log(e)
    var that = this
    var pcarts = []
    for(let i =0; i<that.data.carts.length; i++) {
        if(that.data.carts[i].selected == true){
            pcarts.push(that.data.carts[i])
        }
    }
    if(pcarts.length == 0){
      wx.showToast({
          title: '请添加商品',
          icon: 'error',
          duration: 2000//持续的时间
        })
    }else{
      var passcarts = JSON.stringify(pcarts) //传递pcarts过去，因为carst保存了所有的数据，pcarts中会将没有选择的水果剔除
      wx.navigateTo({
        url: "/pages/jump/jump?carts="+passcarts+"&totalPrice="+that.data.totalPrice,
      })
    }
    
  },
  

 async getweight(){
    var that = this
     wx.showLoading()

    await wx.cloud.callFunction({
      name: 'iothub-shadow-query',
      data: {
            ProductId: app.globalData.productId,
            DeviceName: app.globalData.deviceName,
            SecretId: app.globalData.secretId,
            SecretKey: app.globalData.secretKey,
          },
    }).then(res =>{
      wx.showToast({
        icon: 'none',
        title: '获取称重信息成功',
      })
      let deviceData = JSON.parse(res.result.Data)
      console.log(deviceData.payload.state.reported)
      
        this.setData({
          stateReported: deviceData.payload.state.reported,
        })
      
      this.data.id = this.data.stateReported.class_num;
      this.data.num = (this.data.stateReported.weight).toFixed(3);
      // that.data.num = that.data.stateReported.weight;
      console.log("that.data.num 3:", that.data.num)
    })

    if(that.data.stateReported.class_num == 20){
      wx.showToast({
        icon: 'error',
        duration: 2000,//持续的时间
        title: '请放置正确种类水果',
       });
       return;
    }else{
      console.log(this.data.id)
      console.log(this.data.num)


    //获取P板数据-水果重量、种类
    //根据种类从数据库提取对应水果种类的价格
      var that = this;
      var addcarts = that.data.carts;
      var id = that.data.id;//stateReported.class_num;  //用定义在里面的id就不能加入路径
      var num = (that.data.num * 0.001).toFixed(3);//stateReported.weight;//p板传来的重量
      // var individualPrice = 0; //单类水果总价
      // var price = 10; //从数据库获取price

    // that.ulike(that.callbackLike);

    const res = await myrequest.myrequest({
      url: 'http://81.71.13.99:8080/test/Fruit_infojson',
      header: {
        'content-type': 'application/json' // 默认值
      },
      data:{
        'FruitId':id,
      },
      method: 'POST',
    })
    that.data.price = res.data.fruitPrice
    that.data.name = res.data.fruitName
    console.log(res.data)
    console.log(this.data.price)
    console.log(this.data.name)

      var obj = {
        // id : 0, //种类号，p板数据
        name: that.data.name,//根据种类号来匹配
        image: '../../image/' + id + '.JPG',//根据种类匹配image中的数据
        num: num, //重量p板数据
        price: that.data.price, //价格从数据库取数据
        selected: true,
        id : id,  //id获取，可以将其加入carts中
        individualPrice: (num * that.data.price).toFixed(2)  //单类水果总价
      }
      addcarts.push(obj)
      this.setData({
        carts: addcarts,
      })
      this.getTotalPrice();

    }

    
},
  

  //控制小灯开关
  switchChange(e) {
    let value = 0
    if (e.detail.value == true) {
      value = 1
    }
    let item = e.currentTarget.dataset.item
    let obj = {
      [`${item}`]: value
    }
    let payload = JSON.stringify(obj)
    JSON.parse
    console.log(payload)
    wx.showLoading()
    wx.cloud.callFunction({
      name: 'iothub-publish',
      data: {
        SecretId: app.globalData.secretId,
        SecretKey: app.globalData.secretKey,
        ProductId: app.globalData.productId,
        DeviceName: app.globalData.deviceName,
        Topic: app.globalData.productId + "/" + app.globalData.deviceName + "/data",
        Payload: payload,
      },
      success: res => {
        wx.showToast({
          icon: 'none',
          title: 'publish完成',
        })
        console.log("res:", res)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: 'publish失败，请连接设备',
        })
        console.error('[云函数] [iotexplorer] 调用失败：', err)
      }
    })  
  },

    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})
